/*
 * Search the given haystack for the given needle
 *
 * Copyright 2023 Odin Kroeger.
 *
 * This file is part of suCGI.
 *
 * suCGI is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Affero General Public License as published
 * by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * suCGI is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General
 * Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with suCGI. If not, see <https://www.gnu.org/licenses/>.
 */

#define _XOPEN_SOURCE 700

#include <assert.h>
#include <stddef.h>

#include "array.h"
#include "types.h"

/*
 * lfind does not accept a pointer to a const-qualified lvalue as "nelp"
 * argument when compiled with -Wcast-qual; array_find does.
 */
const void *
array_find(const void *const needle, const void *const haystack,
           const size_t len, const size_t width, const CompFn cmp)
{
    assert(needle != NULL);
    assert(haystack != NULL);
    assert(width > 0U);

    /* cppcheck-suppress misra-c2012-11.5; alignment is not an issue here */
    const char *ptr = (const char *) haystack;

    for (size_t i = 0U; i < len; ++i) {
        if (cmp(needle, (const void *) ptr) == 0) {
            return ptr;
        }

        /* cppcheck-suppress [misra-c2012-10.3, misra-c2012-18.4] */
        ptr += width;
    }

    return NULL;
}
